package com.job;

import com.common.utils.AreaUtil;
import com.common.utils.DateUtils;
import com.common.utils.SysConfig;
import com.model.domain.device.*;
import com.model.pojo.device.*;
import com.service.device.*;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @Description
 * @Author tm
 * @Date 2023-05-25 22:22
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class DevicePmdJob {
    private final DevicePmdBaseInfoService devicePmdBaseInfoService;
    private final DevicePmdDayInfoService devicePmdDayInfoService;
    private final DevicePmdGpsInfoService devicePmdGpsInfoService;
    private final DevicePmdWorkDailyRecordInfoService devicePmdWorkDailyRecordInfoService;
    private final DevicePmdWorkRecordDetailInfoService devicePmdWorkRecordDetailInfoService;
    /**
     * 统计每天的GPS信息
     * @author tm
     * @date 2023-05-25 22:23
     */
    @Scheduled(cron = "0 30 1 * * ?")
    public void countEveryDayPmdGpsInfo(){
        if(SysConfig.getJobSwitch()==0)return;
        Date date = new Date();
        for(int i=1;i<2;i++){
            List<DevicePmdDayInfo> dayList = new ArrayList<>();
            String tableName = "device_pmd_gps_info_";
            date = DateUtils.addDays(date,-1);
            int year = Integer.parseInt(DateUtils.getYear(date));
            int month = Integer.parseInt(DateUtils.getMonth(date));
            int day = Integer.parseInt(DateUtils.getDate(date));
            String dayStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,date);
            dayStr = dayStr.replaceAll("-", "");
            GetDevicePmdGpsInfoDO getDevicePmdGpsInfoDO = new GetDevicePmdGpsInfoDO();
            getDevicePmdGpsInfoDO.setTableName(tableName+dayStr);
            List<Map<String,Object>> list = devicePmdGpsInfoService.getListGroupBy(getDevicePmdGpsInfoDO);
            if(list!=null && list.size()>0){
                list.forEach(item ->{
                    String dtu = (String)item.get("dtu");
                    DevicePmdDayInfo dayInfo = new DevicePmdDayInfo();
                    dayInfo.setDtu(dtu);
                    dayInfo.setYear(year);
                    dayInfo.setMonth(month);
                    dayInfo.setDay(day);
                    dayInfo.setCreatedTime(new Date());
                    dayList.add(dayInfo);
                });
            }

            if(dayList!=null && dayList.size()>0){
                devicePmdDayInfoService.saveList(dayList);
            }
        }
    }

    /**
     * 更新PCB设备的在线状态
     * @author tm
     * @date 2023-05-27 10:10
     */
    @Scheduled(cron = "0 */3 * * * ?")
    public void updatePmdOnLineStatus(){
        if(SysConfig.getJobSwitch()==0)return;
        GetDevicePmdBaseInfoDO getDevicePmdBaseInfoDO = new GetDevicePmdBaseInfoDO();
        getDevicePmdBaseInfoDO.setSortRow("createTime");
        getDevicePmdBaseInfoDO.setSortOrder("desc");
        List<DevicePmdBaseInfo> baseList = devicePmdBaseInfoService.getAllList(getDevicePmdBaseInfoDO);
        List<DevicePmdBaseInfo> updateBaseList = new ArrayList<>();
        if(baseList!=null && baseList.size()>0){
            for(DevicePmdBaseInfo baseInfo:baseList){
                int onLineStatus = 1;//在线状态，0离线，1在线
                if(baseInfo.getLastDataTime()!=null){
                    String time1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date());
                    String time2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,baseInfo.getLastDataTime());
                    List<Long> list = DateUtils.getDistanceTime(time1,time2);
                    if(list.get(0)>0||list.get(1)>0||list.get(2)>1)onLineStatus = 0;
                }else{
                    onLineStatus = 0;
                }
                if(baseInfo.getOnLineStatus() ==null || onLineStatus!=baseInfo.getOnLineStatus()){
                    baseInfo.setOnLineStatus(onLineStatus);
                    updateBaseList.add(baseInfo);
                }
            }
            if(updateBaseList.size()>0){
                devicePmdBaseInfoService.updateList(updateBaseList);
            }
            System.out.println("PMD在线状态更新完成");
        }
    }

    //已废弃
//    @Scheduled(cron = "0 0 2 * * ?")
    public void calWorkArea() {
        if(SysConfig.getJobSwitch()==0)return;
        Date date = new Date();
        for (int i = 1; i < 2; i++) {
            try {
                List<DevicePcbDayInfo> dayList = new ArrayList<>();
                String tableName = "device_pmd_gps_info_";
                date = DateUtils.addDays(date, -1);
                String dayStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
                dayStr = dayStr.replaceAll("-", "");
                GetDevicePmdGpsInfoDO getDevicePmdGpsInfoDO = new GetDevicePmdGpsInfoDO();
                getDevicePmdGpsInfoDO.setTableName(tableName + dayStr);
                List<Map<String, Object>> list = devicePmdGpsInfoService.getListGroupBy(getDevicePmdGpsInfoDO);
                if (list != null && list.size() > 0) {
                    List<DevicePmdWorkDailyRecordInfo> recordList = new ArrayList<>();
                    for (int j = 0; j < list.size(); j++) {
                        Map<String, Object> item = list.get(j);
                        DevicePmdWorkDailyRecordInfo recordInfo = new DevicePmdWorkDailyRecordInfo();
                        double area = 0;
                        String dtu = (String) item.get("dtu");
                        getDevicePmdGpsInfoDO.setDtu(dtu);
                        getDevicePmdGpsInfoDO.setSortRow("time");
                        getDevicePmdGpsInfoDO.setSortOrder("desc");
                        List<DevicePmdGpsInfo> gpsList = devicePmdGpsInfoService.getAllList(getDevicePmdGpsInfoDO);
                        if (gpsList != null && gpsList.size() > 0) {
                            DevicePmdGpsInfo gpsInfo = gpsList.get(0);
                            if(gpsInfo.getArea()!=null && gpsInfo.getArea()!="")
                                area = Double.parseDouble(gpsInfo.getArea());
                        }
                        BigDecimal bigDecimal = new BigDecimal(area + "").setScale(2, BigDecimal.ROUND_HALF_UP);
                        recordInfo.setArea(bigDecimal.toString());
                        recordInfo.setDtu(dtu);
                        recordInfo.setWorkDate(date);
                        recordInfo.setCreatedTime(new Date());
                        recordList.add(recordInfo);
                    }
                    if (recordList.size() > 0) {
                        devicePmdWorkDailyRecordInfoService.saveList(recordList);
                        System.out.println("=====保存作业日报");
                    }

                    System.out.println("PMD日报生成：||||||||||||||||||||| "+DateUtils.parseDateToStr(date,DateUtils.DATE_FORMAT_YYYY_MM_DD));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 每天一点统计前一天设备的日报信息
     * @author tm
     * @date 2024-01-10 8:03
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void statisticsWorkInfo() {
        Date date = new Date();
        date = DateUtils.addDate(date,0,0,-1,0,0,0,0);
        date = DateUtils.parseStrToDate(DateUtils.parseDateToStr(DateUtils.DATE_FORMAT_YYYY_MM_DD,date),DateUtils.DATE_FORMAT_YYYY_MM_DD);
        List<Map<String,Object>> dtuList = devicePmdWorkRecordDetailInfoService.getListGroupBy(date);
        if(dtuList!=null && dtuList.size()>0){
            for(Map<String,Object> map :dtuList){
                String dtu = map.get("dtu").toString();
                GetDevicePmdWorkRecordDetailInfoDO getDevicePmdWorkRecordDetailInfoDO = new GetDevicePmdWorkRecordDetailInfoDO();
                getDevicePmdWorkRecordDetailInfoDO.setDtu(dtu);
                getDevicePmdWorkRecordDetailInfoDO.setWorkDate(date);
                List<DevicePmdWorkRecordDetailInfo> detailList = devicePmdWorkRecordDetailInfoService.getAllList(getDevicePmdWorkRecordDetailInfoDO);
                if(detailList!=null &&detailList.size()>0){
                    double area = 0;
                    int totalSeedNum = 0;
                    int totalMissedNum = 0;
                    DevicePmdWorkDailyRecordInfo info = new DevicePmdWorkDailyRecordInfo();
                    info.setDtu(dtu);
                    info.setWorkDate(date);
                    for(DevicePmdWorkRecordDetailInfo detailInfo:detailList){
                        area+=Double.parseDouble(detailInfo.getArea());
                        totalSeedNum+=Integer.parseInt(detailInfo.getTotalSeedNum());
                        totalMissedNum+= Integer.parseInt(detailInfo.getTotalMissedNum());
                    }
                    info.setArea(area+"");
                    info.setTotalSeedNum(totalSeedNum+"");
                    info.setTotalMissedNum(totalMissedNum+"");
                    devicePmdWorkDailyRecordInfoService.save(info);
                }
            }
        }
    }
}
